﻿@model ShipmentListModel
           
@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;


    //page title
    ViewBag.Title = T("Admin.Orders.Shipments.List").Text;
}

@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Orders.Shipments.List")
        </div>
        <div class="options">
            <a href="@Url.Action("PdfPackagingSlipAll")" class="k-button">@T("Admin.Orders.Shipments.PrintPackagingSlip.All")</a>
            <input type="button" id="exportpackagingslips-selected" class="k-button" value="@T("Admin.Orders.Shipments.PrintPackagingSlip.Selected")" />
            <input type="button" id="ship-selected" class="k-button" value="@T("Admin.Orders.Shipments.ShipSelected")" />
            <input type="button" id="deliver-selected" class="k-button" value="@T("Admin.Orders.Shipments.DeliverySelected")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.TrackingNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.TrackingNumber)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CountryId):
            </td>
            <td class="adminData">
               @Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StateProvinceId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.StateProvinceId, Model.AvailableStates)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.City):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.City)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.WarehouseId):
            </td>
            <td class="adminData">
                @Html.DropDownList("WarehouseId", Model.AvailableWarehouses)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="k-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
     <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                <div id="shipments-grid"></div>

                <script>
                    $(document).ready(function () {
                        $("#shipments-grid").kendoGrid({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("ShipmentListSelect", "Order"))",
                                        type: "POST",
                                        dataType: "json",
                                        data: additionalData
                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors"
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                pageSize: @(defaultGridPageSize),
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            pageable: {
                                refresh: true,
                                pageSizes: [@(gridPageSizes)]
                            },
                            //details grid
                            detailInit: detailInit,
                            scrollable: false,
                            dataBound: onDataBound,
                            columns: [{
                                field: "Id",
                                headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                width: 50
                            }, {
                                field: "Id",
                                title: "@T("Admin.Orders.Shipments.ID")",
                                width: 50
                            }, {
                                field: "OrderId",
                                title: "@T("Admin.Orders.Shipments.OrderID")",
                                width: 100
                            }, {
                                field: "TrackingNumber",
                                title: "@T("Admin.Orders.Shipments.TrackingNumber")",
                                width: 100
                            }, {
                                field: "TotalWeight",
                                title: "@T("Admin.Orders.Shipments.TotalWeight")",
                                width: 100
                            }, {
                                field: "ShippedDate",
                                title: "@T("Admin.Orders.Shipments.ShippedDate")",
                                width: 200,
                                type: "date",
                                format: "{0:G}"
                            }, {
                                field: "DeliveryDate",
                                title: "@T("Admin.Orders.Shipments.DeliveryDate")",
                                width: 200,
                                type: "date",
                                format: "{0:G}"
                            }, {
                                field: "Id",
                                title: "@T("Admin.Common.View")",
                                width: 50,
                                template: '<a href="@Url.Content("~/Admin/Order/ShipmentDetails/")#=Id#">@T("Admin.Common.View")</a>'
                            }]
                        });
                    });

                    //details grid
                    function detailInit(e) {
                        $("<div/>").appendTo(e.detailCell).kendoGrid({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("ShipmentsItemsByShipmentId", "Order"))?shipmentId="+e.data.Id,
                                        type: "POST",
                                        dataType: "json"
                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors"
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            scrollable: false,
                            sortable: true,
                            pageable: {
                                refresh: true,
                                numeric: false,
                                previousNext: false,
                                info: false
                            },
                            columns: [
                                {
                                    field: "ProductName",
                                    title: "@T("Admin.Orders.Shipments.Products.ProductName")",
                                    width: 400
                                },{
                                    field: "Warehouse",
                                    title: "@T("Admin.Orders.Shipments.Products.Warehouse")",
                                    width: 150
                                },{
                                    field: "QuantityInThisShipment",
                                    title: "@T("Admin.Orders.Shipments.Products.QtyShipped")",
                                    width: 150
                                },{
                                    field: "ItemWeight",
                                    title: "@T("Admin.Orders.Shipments.Products.ItemWeight")",
                                    width: 150
                                },{
                                    field: "ItemDimensions",
                                    title: "@T("Admin.Orders.Shipments.Products.ItemDimensions")",
                                    width: 150
                                }
                            ]
                        });
                    }
                </script>
            </td>
        </tr>
    </table>
    
    <script type="text/javascript">

        var selectedIds = [];

        $(document).ready(function () {

            //load states when changing a country dropdownlist
            $("#@Html.FieldIdFor(model => model.CountryId)").change(function () {
                var selectedItem = $(this).val();
                var ddlStates = $("#@Html.FieldIdFor(model => model.StateProvinceId)");
                $.ajax({
                    cache: false,
                    type: "GET",
                    url: "@(Url.Action("GetStatesByCountryId", "Country"))",
                    data: { "countryId": selectedItem, "addAsterisk": "true" },
                    success: function (data) {
                        ddlStates.html('');
                        $.each(data, function (id, option) {
                            ddlStates.append($('<option></option>').val(option.id).html(option.name));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.');
                    }
                });
            });

            $("#@Html.FieldIdFor(model => model.TrackingNumber)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#btnSearch").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.City)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#btnSearch").click();
                    return false;
                }
            });
            
            //search button
            $('#btnSearch').click(function () {
                //search
                var grid = $('#shipments-grid').data('kendoGrid');
                grid.dataSource.page(1); //new search. Set page size to 1
                grid.dataSource.read();
                //clear selected checkboxes
                $('.checkboxGroups').attr('checked', false).change();
                selectedIds = [];
                return false;
            });


            //"ship selected" button
            $('#ship-selected').click(function(e) {
                e.preventDefault();

                var postData = {
                    selectedIds: selectedIds
                };

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "@(Url.Action("SetAsShippedSelected", "Order"))",
                    data: postData,
                    complete: function(data) {
                        //reload grid
                        var grid = $('#shipments-grid').data('kendoGrid');
                        //grid.dataSource.page(1); //new search. Set page size to 1
                        grid.dataSource.read();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    },
                    traditional: true
                });
                return false;
            });

            //"deliver selected" button
            $('#deliver-selected').click(function(e) {
                e.preventDefault();

                var postData = {
                    selectedIds: selectedIds
                };

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "@(Url.Action("SetAsDeliveredSelected", "Order"))",
                    data: postData,
                    complete: function(data) {
                        //reload grid
                        var grid = $('#shipments-grid').data('kendoGrid');
                        //grid.dataSource.page(1); //new search. Set page size to 1
                        grid.dataSource.read();
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    },
                    traditional: true
                });
                return false;
            });

            
            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes. 
            $('#shipments-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.  
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.  
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

        function additionalData() {
            return {
                StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                TrackingNumber: $('#@Html.FieldIdFor(model => model.TrackingNumber)').val(),
                CountryId: $('#@Html.FieldIdFor(model => model.CountryId)').val(),
                StateProvinceId: $('#@Html.FieldIdFor(model => model.StateProvinceId)').val(),
                City: $('#@Html.FieldIdFor(model => model.City)').val(),
                WarehouseId: $('#@Html.FieldIdFor(model => model.WarehouseId)').val()
            };
        }
    
        function onDataBound(e) {

            $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.  
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#shipments-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
            $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }
   </script>
    
}

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("PdfPackagingSlipSelected", "Order", FormMethod.Post, new { id = "pdf-packaging-slip-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#exportpackagingslips-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#pdf-packaging-slip-selected-form #selectedIds').val(ids);
            $('#pdf-packaging-slip-selected-form').submit();
            return false;
        });
    });

</script>